package com.atguigu.gmall.order.interceptor;


import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.order.vo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;


//@Scope("prototype")
@Component
public class OrderInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username = CookieUtils.getCookieValue(request, "unick");
        Long userId = Long.valueOf(CookieUtils.getCookieValue(request, "userId"));
        username = URLDecoder.decode(username, "UTF-8");
        THREAD_LOCAL.set(new UserInfo(userId,username));
        return true;
    }

    //定义一个返回参数的方法
    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放资源
        THREAD_LOCAL.remove();
    }
}
